package com.example.yilanchatserver.application.config;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * 配置使用jackson序列化
 */
@Configuration
public class HttpMessageConverterConfig implements WebMvcConfigurer {


    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = new ObjectMapper();
        //时间格式统一，特别的可用JsonFormat注解
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        converter.setObjectMapper(objectMapper);
        //自定义null序列化
        //MappingJackson2HttpMessageConverter 默认对null对象 返回的null，不属于任何类型的。并且没有对null对象做区分管理（例如
        // 空数组返回[] ,空map返回{} ,如果需要这中的，可以自定义NullValueSerializer）
        objectMapper.getSerializerProvider().setNullValueSerializer(new NullJsonSerializer());
        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
//        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);//为null的字段自动屏蔽下，不返回
        //优先级高于springboot auto config 的
        converters.add(0, converter);
    }

    public class NullJsonSerializer extends JsonSerializer<Object> {
        @Override
        public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
            //空值直接返回空串
            jsonGenerator.writeString(StringUtils.EMPTY);
        }
    }


}
